package springboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 调用时默认调用该序列化方式,redis的调用工具类
 */
@Configuration
public class RedisConfig {

    @Primary
    @Bean
    public RedisTemplate<String,Object> getRedisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String,Object> redisTemplate=new RedisTemplate();
        redisTemplate.setConnectionFactory(factory);
        /*设置string键值的序列化方式*/
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //String类型的作为json串来传递数据更好
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        /*设置hash的键值序列化方式*/
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
        return redisTemplate;
    }
}
